<template>
	<view class="chosen-position select-menu" @click="handlePositionClick">
		<template v-if="position.address">
			<view class="value">
				{{ position.recommend }}
				<view class="desc">
					{{ position.address }}
				</view>
			</view>
		</template>
		<template v-else>
			<view class="placeholder">
				请选择收货地址
			</view>
		</template>
		<image class="right-icon" src="@/static/image/right.png"></image>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import QQMapWx from '@/utils/qqmap-wx-jssdk.min.js'
	const props = defineProps({
		position: {
			type: Object,
			default: () => {}
		}
	})
	// const position = ref()
	const handlePositionClick = () => {
		console.log('选择地址');
		uni.getSetting({
			success: (res) => {
				console.log(res);
				if (res.authSetting['scope.userFuzzyLocation']) {
					// 用户授权获取定位
					chooseLocation()
				} else if (res.authSetting['scope.userFuzzyLocation'] === undefined) {
					// 用户没有授权
					handleOpenSetting()
				} else {
					// 用户决绝授权
					handleOpenSetting()
				}
			}
		})
	}
	const emits = defineEmits(['change'])
	const qqmapsdk = new QQMapWx({
		key: 'O3BBZ-F4TCK-6B3JM-ATT6Q-YALXS-SYFDJ'
	})
	const chooseLocation = () => {
		uni.chooseLocation({
			success: (e) => {
				qqmapsdk.reverseGeocoder({
					location: {
						latitude: e.latitude,
						longitude: e.longitude
					},
					success: (res) => {
						console.log(res);
						emits('change', {
							...res.result.address_component,
							...res.result.location,
							address: res.result.address,
							recommend: res.result.formatted_addresses.recommend
						})
					},
					fail: (e) => {
						console.log('失败', e);
					}
				})
			},
			fail: (err) => {
				console.log(err);
			}
		})
	}
	const handleOpenSetting = () => {
		console.log('打开授权页面');
		uni.authorize({
			scope: 'scope.userFuzzyLocation',
			success: () => {
				console.log('用户同意授权');
				chooseLocation()
			},
			fail: (err) => {
				uni.showModal({
					title: '提示',
					content: '请授权， 否则无法发布宠物出行',
					confirmText: '去授权',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting({
								success: (res) => {
									if (res.authSetting['scope.userFuzzyLocation']) {
										console.log('授权');
										chooseLocation()
									}
								}
							})
						}
					}
				})
			}
		})
	}
</script>

<style lang="scss" scoped>
	.chosen-position {

		.value {
			text-align: right;
			font-family: PingFang SC, PingFang SC;
			color: #2C1F21;
			width: calc(100% - 40rpx);
			font-size: 28rpx;

			.desc {
				font-family: PingFang SC, PingFang SC;
				color: #A6A1A1;
				font-size: 24rpx;
			}
		}

		.value,
		.desc {
			font-weight: 400;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}

		.placeholder {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #A6A1A1;
			line-height: 33rpx;
		}
	}
</style>